package sss.lru;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program: java-interview
 * @description: lru算法
 * @author: DingZhenYun
 * @create: 2021-11-11 19:33
 **/

public class LRUCacheDemo<K, V> extends LinkedHashMap<K, V> {

    // 缓存容量
    private int capacity;

    public LRUCacheDemo(int capacity) {
        super(capacity, 0.75F, true);
        this.capacity=capacity;
    }

    // 用于判断是否需要删除最近最久未使用的节点
    @Override
    protected boolean removeEldestEntry (Map.Entry < K, V > eldest){
        return super.size() > capacity;
    }

    public static void main (String[]args){
        LRUCacheDemo lruCacheDemo = new LRUCacheDemo(3);

        lruCacheDemo.put(1, "a");
        lruCacheDemo.put(2, "b");
        lruCacheDemo.put(3, "c");
        System.out.println(lruCacheDemo.keySet());

        lruCacheDemo.put(4, "d");
        System.out.println(lruCacheDemo.keySet());

        lruCacheDemo.put(3, "c");
        System.out.println(lruCacheDemo.keySet());
        lruCacheDemo.put(3, "c");
        System.out.println(lruCacheDemo.keySet());
        lruCacheDemo.put(3, "c");
        System.out.println(lruCacheDemo.keySet());
        lruCacheDemo.put(5, "x");
        System.out.println(lruCacheDemo.keySet());
    }
}
